<?php

namespace app\admin\controller\auth;

use app\admin\model\AuthDepartment;
use app\admin\model\AuthGroup;
use app\admin\model\AuthGroupAccess;
use app\common\controller\Backend;
use Overtrue\Pinyin\Pinyin;
use fast\Random;
use fast\Tree;
use think\Db;
use app\admin\model\Admin as WorkAdmin;

/**
 * 管理员管理
 *
 * @icon fa fa-users
 * @remark 一个管理员可以有多个角色组,左侧的菜单根据管理员所拥有的权限进行生成
 */
class Admin extends Backend
{

    protected $searchFields = 'id,username,mobile';
    protected $model = null;
    protected $childrenGroupIds = [];
    protected $childrenAdminIds = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Admin');
        $this->view->assign("genderList", $this->model->getGenderList());
        $this->view->assign("isleaderList", $this->model->getIsleaderList());
        $this->view->assign("departmentList", $this->model->getDepartmentList());
        $this->view->assign("deletestatusList", $this->model->getDeleteStatusList());
        $this->view->assign("getzhengshiList", $this->model->getZhengshiList());
        $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds(true);
        $groupList = collection(AuthDepartment::field('*,parentid as pid')->select())->toArray();
        //$groupList = collection(AuthDepartment::field('*,parentid as pid')->where('id', 'in', $this->childrenGroupIds)->select())->toArray();

        Tree::instance()->init($groupList);
        $groupdata = [];
        if ($this->auth->isSuperAdmin())
        {
            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
            foreach ($result as $k => $v)
            {
                $groupdata[$v['id']] = $v['name'];
            }
        }
        else
        {
            $result = [];
            $groups = $this->auth->getGroups();
            var_dump($groups);
            foreach ($groups as $m => $n)
            {
                $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['id']));
                $temp = [];
                foreach ($childlist as $k => $v)
                {
                    $temp[$v['id']] = $v['name'];
                }
                $result[__($n['name'])] = $temp;
            }
            $groupdata = $result;
        }

        $this->view->assign('groupdata', $groupdata);
        $this->assignconfig("admin", ['id' => $this->auth->id]);
        $position_data = array_column(collection(AuthGroup::field('id,name')->order('weigh', 'desc')->select())->toArray(), 'name','id');
        //职位信息
        unset($position_data[1]);//销毁管理员
        $this->view->assign('position_data',$position_data);
    }

    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                print_r($this->request->request('keyField'));exit;
                return $this->selectpage();
            }
            $childrenGroupIds = $this->childrenGroupIds;
            $groupName = AuthGroup::where('id', 'in', $childrenGroupIds)->order('weigh', 'desc')
                ->column('id,name');
            $authGroupList = AuthGroupAccess::where('group_id', 'in', $childrenGroupIds)
                ->field('uid,group_id')
                ->select();

            $adminGroupName = [];
            foreach ($authGroupList as $k => $v)
            {
                if (isset($groupName[$v['group_id']]))
                    $adminGroupName[$v['uid']][$v['group_id']] = $groupName[$v['group_id']];
            }
            $groups = $this->auth->getGroups();
            foreach ($groups as $m => $n)
            {
                $adminGroupName[$this->auth->id][$n['id']] = $n['name'];
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where('id', 'in', $this->childrenAdminIds)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->where('id', 'in', $this->childrenAdminIds)
                ->field(['password', 'salt', 'token'], true)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $k => &$v)
            {
                $groups = isset($adminGroupName[$v['id']]) ? $adminGroupName[$v['id']] : [];
                $v['groups'] = implode(',', array_keys($groups));
                $v['groups_text'] = implode(',', array_values($groups));
            }
            unset($v);
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }

        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            $params['department'] = $this->request->post("department/a");
            if ($params)
            {
                $params['salt'] = Random::alnum();
                $params['password'] ? null : $params['password'] = 123456;
                $params['password'] = md5(md5($params['password']) . $params['salt']);
                $params['avatar'] = '/assets/img/avatar.png'; //设置新管理员默认头像。
                $params['publish']    = \think\Session::get('admin')['userid'];
                $params['z_publish']    = \think\Session::get('admin')['userid'];
                $params['status']    = 'Hidden';//默认禁用
                $params['alias'] = $params['nickname'];//别名

                $result = $this->model->validate('Admin.add')->save($params);
                if ($result === false)
                {
                    $this->error($this->model->getError());
                }
                $group = $this->request->post("group/a");
                //过滤不允许的组别,避免越权
                $group = array_intersect($this->childrenGroupIds, $group);
                $dataset = [];

                //添加到企业微信
                $params['name'] = $params['username'];
                $params['to_invite'] = true;//是否邀请该成员使用企业微信
                $params['userid'] = $this->UserId($params['username']).$this->model->id;
                $params['department'] = implode(',',$params['department']);//部门

                if(!empty($params['id_number']) || !empty($params['card_number']) || !empty($params['is_zhengshi'])){
                    $is_zhengshi = $params['is_zhengshi'] == 1 ? '否' :'是';
                    $params['extattr']['attrs'] = [
                                 0=>['name'=>'身份证号','value'=>$params['id_number']],
                                 1=>['name'=>'银行卡号','value'=>$params['card_number']],
                                 2=>['name'=>'是否转正','value'=>$is_zhengshi],
                            ];
					unset($is_zhengshi);
                }
				
                unset($params['card_number'],$params['id_number'],$params['z_publish'],$params['status'],$params['publish'],$params['englishname'],$params['password'],$params['salt'],$params['username'],$params['nickname'],$params['avatar'],$params['status']);
                $result = WorkAdmin::workAdd(array_filter($params));
                if($result['errcode'] > 0)
                {
                    //删除本地用户
                    $this->del($this->model->id);
                    $this->error('添加失败！');
                }

                foreach ($group as $value)
                {
                    $dataset[] = ['uid' => $this->model->id, 'group_id' => $value,'userid'=>$params['userid']];
                }
                model('AuthGroupAccess')->saveAll($dataset);

                WorkAdmin::update(['userid'=>$params['userid']],['id'=>$this->model->id]);
//                AuthGroupAccess::update(['userid'=>$params['userid']],['id'=>$this->model->id]);
                $this->success();
            }
            $this->error();
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row)
            $this->error(__('No Results were found'));
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            $params['department'] = $this->request->post("department/a");
            if ($params)
            {
                $data = $params;
                unset($data['status'],$data['password'],$data['id_number'],$data['card_number']);

                 if(!empty($params['id_number']) || !empty($params['card_number']) || !empty($params['is_zhengshi'])  ){
                    $is_zhengshi = $params['is_zhengshi'] == 1 ? '否' :'是';
                    $data['extattr']['attrs'] = [
                                 0=>['name'=>'身份证号','value'=>$params['id_number']],
                                 1=>['name'=>'银行卡号','value'=>$params['card_number']],
                                 2=>['name'=>'是否转正','value'=>$is_zhengshi],
                            ];
					unset($is_zhengshi);
                }
                $result = WorkAdmin::updateAdmin($row->userid,array_filter($data));//企业微信同步
                if($result['errcode'] > 0)
                {
                    $this->error(GetErrorLang($result['errcode'],$result));
                }
                $params['department'] = implode(',',$params['department']);
                if ($params['password'])
                {
                    $params['salt'] = Random::alnum();
                    $params['password'] = md5(md5($params['password']) . $params['salt']);
                }
                else
                {
                    unset($params['password'], $params['salt']);
                }
                //这里需要针对username和email做唯一验证
                $adminValidate = \think\Loader::validate('Admin');
                $adminValidate->rule([
//                    'username' => 'require|max:50|unique:admin,username,' . $row->id,
//                    'email'    => 'require|email|unique:admin,email,' . $row->id,
                      'id_number' => 'require|max:50|unique:admin,id_number,' . $row->id,
                      'card_number' => 'require|max:50|unique:admin,card_number,' . $row->id,
                ]);
                $result = $row->validate('Admin.edit')->save($params);
                if ($result === false)
                {
                    $this->error($row->getError());
                }
                // 先移除所有权限
                model('AuthGroupAccess')->where('uid', $row->id)->delete();
                //移除企业微信标签
                if($this->childrenGroupIds)
                {
                    foreach ($this->childrenGroupIds as $item)
                    {
                        AuthGroup::delTabUser($item,[$row->userid]);//删除标签成功
                    }
                }

                $group = $this->request->post("group/a");
                // 过滤不允许的组别,避免越权
                $group = array_intersect($this->childrenGroupIds, $group);
                $dataset = [];
                foreach ($group as $value)
                {
                    $dataset[] = ['uid' => $row->id, 'group_id' => $value,'userid'=>$row->userid];
                    AuthGroup::updateTabUser($value,[$row->userid]);//增加标签成员
                }

                model('AuthGroupAccess')->saveAll($dataset);
                $this->success();
            }
            $this->error();
        }
        $grouplist = $this->auth->getGroups($row['id']);//标签
        $groupids = [];
        foreach ($grouplist as $k => $v)
        {
            $groupids[] = $v['id'];
        }
        $row['department'] = explode(',',$row['department']);
        $this->view->assign("row", $row);
        $this->view->assign("groupids", $groupids);
        return $this->view->fetch();
    }
    public function shows($ids = NULL){
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost())
        {
            $data = $this->request->post("row/a");
            $result = $row->allowField(true)->save($data);
            $this->success();
        }
        $feixiao = array('按提成结算','一套1块','一套2块','一套3块','一套4块');
        $this->view->assign("feixiao", $feixiao);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids)
        {
            $row = $this->model->get(['id' => $ids]);
            // 避免越权删除管理员
            $childrenGroupIds = $this->childrenGroupIds;
            $adminList = $this->model->where('id', 'in', $ids)->where('id', 'in', function($query) use($childrenGroupIds) {
                $query->name('auth_group_access')->where('group_id', 'in', $childrenGroupIds)->field('uid');
            })->select();
            if ($adminList)
            {
                $deleteIds = [];
                foreach ($adminList as $k => $v)
                {
                    $deleteIds[] = $v->id;
                }
                $deleteIds = array_diff($deleteIds, [$this->auth->id]);
                if ($deleteIds)
                {
                    $this->model->destroy($deleteIds);
                    model('AuthGroupAccess')->where('uid', 'in', $deleteIds)->delete();
                    //没有批量删除操作
                    WorkAdmin::deleteAdmin($row['userid']);
                    $this->success();
                }
            }
        }
        $this->error();
    }


    /*
     * 中文转拼音
     */
    public function UserId($name)
    {
        $pinyin = new Pinyin();
        $array = $pinyin->convert($name);
        $userId = '';
        foreach ($array as $value)
        {
            $userId .=$value;
        }
        return $userId;
    }


    public function updateall()
    {
        $data = WorkAdmin::listAdmin();
        if($data['errcode'] > 0)
        {
            $this->error(GetErrorLang($data['errcode']));
        }
    
        $result = $this->dataAttr($data['userlist']);
        Db::execute('truncate table `hdyj_admin`');
        $admin = new WorkAdmin();
        $res = $admin->saveAll($result,false);
        Db::execute('truncate table `hdyj_auth_group_access`');
        $group = WorkAdmin::groupUpdate();
        $groupAccess = new AuthGroupAccess();
        $groupAccess->saveAll($group,false);
        $this->success('同步完成！');
    }

    public function dataAttr($data)
    {

        if($this->auth->id !== 1)
        {
            $this->error('没有权限,请联系管理员！');
        }
        $data = array_merge([
            [
                'department'=>[1],
                'name'=>'admin',
                'alias'=>'admin',
                'extattr'=>'',
                'position'=>'',
                'mobile'=>'',
                'gender'=>'',
                'email'=>'',
                'avatar'=>'/assets/img/avatar.png',
                'delete_status'=>1,
                'status'=>'Normal',//禁用
                'enable'=>'',
                'isleader'=>'',
                'english_name'=>'',
                'telephone'=>'',
                'hide_mobile'=>'',
                'order'=>'',
                'qr_code'=>'',
                'userid'=>1,
                'id_number'=>'',
                'card_number'=>'',
                'is_zhengshi'=>'',
                'password'=>'hdyjoa'
            ]
        ],$data);
        foreach ($data as &$value)
        {
            $value['department'] = implode(',',$value['department']);
            $value['username'] = $value['name'];
            $value['nickname'] = $value['alias'];
            $value['salt'] = Random::alnum();
            $value['delete_status'] = $value['status'];//企业微信状态
            $value['status'] = $value['name'] == 'admin' ? 'Normal' :'Normal';
            if($value['name'] != 'admin') $value['password']  = 123456;
            $value['password'] = md5(md5($value['password']) . $value['salt']);
            if(isset($value['extattr']['attrs'])){
				$value['extattr']['attrs'] = array_column($value['extattr']['attrs'],'value','name');
				if(isset($value['extattr']['attrs']['身份证号'])){
					$value['id_number'] = $value['extattr']['attrs']['身份证号'];
				}
				if(isset($value['extattr']['attrs']['银行卡号'])){
					$value['card_number'] = $value['extattr']['attrs']['银行卡号'];
				}
                if(isset($value['extattr']['attrs']['是否转正'])){
                    $value['is_zhengshi'] = $value['extattr']['attrs']['是否转正'];
                }
            }
            unset($value['extattr'],$value['hide_mobile'],$value['order'],$value['name'],$value['alias'],$value['is_leader_in_dept'],$value['address'],$value['external_profile'],$value['external_position'],$value['main_department']);//销毁没用的变量
        }
        return $data;
    }
    public function import(){
        return parent::import();
    }

    /**
     * 批量更新
     * @internal
     */
    public function multi($ids = "")
    {
        // 管理员禁止批量操作
        $this->error();
    }

    /**
     * 下拉搜索
     */
    public function selectpage()
    {
        return parent::selectpage();
    }

    /**
     * 下拉搜索，带职位
     * @return \think\response\Json
     */
    public function selectDepartment()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr", "and", "strtoupper");
        //排序方式
        $orderby = (array)$this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array)$this->request->request("searchField/a");
        //自定义搜索条件
        $custom = (array)$this->request->request("custom/a");
        $order = [];
        foreach ($orderby as $k => $v) {
            $order[$v[0]] = $v[1];
        }

        $field = $field ? $field : 'username';

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null) {
            $where = [$primarykey => ['in', $primaryvalue]];
        } else {
            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
                $logic = $andor == 'AND' ? '&' : '|';
                $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
                foreach ($word as $k => $v) {
                    $query->where(str_replace(',', $logic, $searchfield), "like", "%{$v}%");
                }
                if ($custom && is_array($custom)) {
                    foreach ($custom as $k => $v) {
                        $query->where($k, '=', $v);
                    }
                }
            };
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = [];
        $total = $this->model->alias('a')
            ->join('hdyj_auth_group_access b','a.id = b.uid','left')
            ->join('hdyj_auth_group c','b.group_id = c.id','left')->where($where)->count();
        if ($total > 0) {
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $order['weigh'] = 'asc';
            $datalist = $this->model->alias('a')
                ->join('hdyj_auth_group_access b','a.id = b.uid','left')
                ->join('hdyj_auth_group c','b.group_id = c.id','left')
                ->where($where)
                ->order($order)
                ->page($page, $pagesize)
                ->field('a.userid,a.username,b.`group_id`,c.`name`,c.weigh,a.gender,a.isleader,a.department,a.delete_status')
                ->select()->toArray();
            foreach ($datalist as $index => $item) {
                $list[] = [
                    $primarykey => isset($item[$primarykey]) ? $item['userid'] : $item['userid'],
                    $field      => isset($item[$field]) ? $item[$field]."(" .$item['name'].")" : '',
                ];
            }
        }
        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => $total]);
    }
}
